package com.ygqh.baby.service.impl;

import com.foxinmy.weixin4j.exception.WeixinException;
import com.foxinmy.weixin4j.http.weixin.JsonResult;
import com.foxinmy.weixin4j.model.MediaDownloadResult;
import com.foxinmy.weixin4j.model.MediaUploadResult;
import com.foxinmy.weixin4j.mp.api.MediaApi;
import com.ygqh.baby.service.WeixinMaterialService;
import com.ygqh.baby.service.WxMpAuthorityService;
import com.ygqh.baby.utils.ImageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.InputStream;

/**
 * 〈〉
 *
 * @author guohao
 * @date 2019/1/11 12:53
 * @since 1.0.0
 */
@Service
public class WeixinMaterialServiceImpl implements WeixinMaterialService {

    @Autowired
    private WxMpAuthorityService wxMpAuthorityService;

    private MediaApi mediaApi;

    @PostConstruct
    private void init() {
        mediaApi = new MediaApi(wxMpAuthorityService.findTokenHolder());
    }

    @Override
    public MediaUploadResult addMaterial(boolean forever, InputStream is, String fileName) throws WeixinException {
        return mediaApi.uploadMedia(forever, is, fileName);
    }

    @Override
    public MediaUploadResult addImageMaterial(boolean forever, String url, String fileName) throws WeixinException {
        InputStream inputStream = ImageUtils.getInputStream(url);

        return this.addMaterial(forever, inputStream, fileName);
    }

    @Override
    public MediaDownloadResult downloadMedia(String mediaId, boolean forever) throws WeixinException {
        MediaDownloadResult mediaDownloadResult = mediaApi.downloadMedia(mediaId, forever);
        return mediaDownloadResult;
    }

    @Override
    public JsonResult deleteMaterial(String mediaId) throws WeixinException {
        return mediaApi.deleteMaterialMedia(mediaId);
    }
}
